package com.tencent.qplus.paddata.stat2;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;

import com.tencent.qplus.paddata.db.DataSourceManager;
import com.tencent.qplus.paddata.stat.Job;
import com.tencent.qplus.paddata.util.ConfigUtil;
import com.tencent.qplus.paddata.util.JdbcUtils;

public class ParseUinListJob extends Job{
	
	private File newUinListFile;
	private File dayLoginUinListFile;
	private static Logger logger = Logger.getLogger(ParseUinListJob.class);
	
	@Override
	public void init() throws Exception{
		String newUinListFilePath = ConfigUtil.getString("newuinlistfilepath");
		String dayLoginUinListFilePath = ConfigUtil.getString("loginuinlistfilepath");
		String dateStr = statDate.replaceAll("-", "");
		newUinListFile = new File(newUinListFilePath+"new_login_" + dateStr + ".txt");
		dayLoginUinListFile = new File(dayLoginUinListFilePath+"day_" + dateStr + ".txt");
	}
	
	
	@Override
	public void run() throws Exception {
		init();
		List<Long> newuins = getNewUinList();
		Connection paddataConn = null;
		Connection padversiondataConn = null;
		
		String insertNewUinSql = "REPLACE INTO padversiondata.newuin (firstLoginDate,uin,loginVersion) VALUES(?,?,?);";
		String insertUinLoingSql = "REPLACE INTO padversiondata.uinlogin_?(uin,logindate,loginVersion) VALUES(?,?,?);";
		Statement st = null;
		ResultSet rs = null;
		PreparedStatement insertNewUinPst = null;
		PreparedStatement insertUinLoingPst = null;
		try {
			paddataConn = DataSourceManager.getInstance().getDataSource("paddatadb").getConnection();
			padversiondataConn = DataSourceManager.getInstance().getDataSource("padversiondatadb").getConnection();
			
			insertNewUinPst = padversiondataConn.prepareStatement(insertNewUinSql);
			insertUinLoingPst = padversiondataConn.prepareStatement(insertUinLoingSql);
			
			int insertNewUinNum=0;
			int insertLoginUinNum=0;
			//循环100张表，获取版本信息
			for(int i=0;i<100;i++){
				logger.info("index:"+i);
				Map<Long,String> uinVersionMap = new HashMap<Long,String>();
				String sql = "SELECT uin,`version` FROM paddata.userinfo_"+i+" WHERE logindate='" + this.statDate + "'";
					st = paddataConn.createStatement();
					rs = st.executeQuery(sql);
					while(rs.next()){
						long uin = Long.parseLong(rs.getString("uin"));
						String version = rs.getString("version");
						uinVersionMap.put(uin, version);
					}
				if(newuins!=null && newuins.size()>0){
					for(Long uin:newuins){
						if(i == uin%100){
							String version = uinVersionMap.get(uin);
							insertNewUinPst.setString(1, statDate);
							insertNewUinPst.setLong(2, uin);
							insertNewUinPst.setString(3, version==null?"-1":version);
							insertNewUinPst.addBatch();
							if(++insertNewUinNum%100 == 0){
								insertNewUinPst.executeBatch();
							}
						}
					}
					insertNewUinPst.executeBatch();
				}
				logger.info("getLoginUinList..");
				List<Long> loginUinList = getLoginUinList(i);
				logger.info("getLoginUinList ok");
				if(loginUinList!=null && loginUinList.size()>0){
					System.out.println("loginUinList:"+loginUinList.size());
					for(Long uin:loginUinList){
						String version = uinVersionMap.get(uin);
						insertUinLoingPst.setInt(1, i);
						insertUinLoingPst.setLong(2, uin);
						insertUinLoingPst.setString(3, statDate);
						insertUinLoingPst.setString(4, version==null?"-1":version);
						insertUinLoingPst.addBatch();
						if(++insertLoginUinNum%1000 == 0){
							insertUinLoingPst.executeBatch();
						}
					}
					insertUinLoingPst.executeBatch();
				}
				logger.info("insert login data ok");
			}
		} catch (SQLException e) {
			logger.error(e);
			throw e;
		}finally{
			JdbcUtils.release(rs);
			JdbcUtils.release(st);
			JdbcUtils.release(insertNewUinPst);
			JdbcUtils.release(insertUinLoingPst);
			JdbcUtils.release(padversiondataConn);
			JdbcUtils.release(paddataConn);
		}
		
	}

	/**
	 * 解析新用户文件
	 * @return
	 */
	private List<Long> getNewUinList() throws Exception{
		try {
			BufferedReader br = new BufferedReader(new FileReader(newUinListFile));
			List<Long> list = new ArrayList<Long>();
			String line = null;
			while((line=br.readLine())!=null){
				list.add(Long.parseLong(line));
			}
			br.close();
			return list;
		} catch (FileNotFoundException e) {
			logger.error(e);
			throw e;
		} catch (NumberFormatException e) {
			logger.error(e);
			throw e;
		} catch (IOException e) {
			logger.error(e);
			throw e;
		}
	}
	
	
	/**
	 * 解析日登录UIN列表文件，取值模100==index的值
	 * 会要读取文件100次
	 * @param index
	 * @return
	 */
	private List<Long> getLoginUinList(int index) throws Exception{
		
		try {
			BufferedReader br = new BufferedReader(new FileReader(dayLoginUinListFile));
			List<Long> list = new ArrayList<Long>();
			String line = null;
			while((line=br.readLine())!=null){
				Long uin = Long.parseLong(line);
				if(uin%100==index){
					list.add(uin);
				}
			}
			br.close();
			return list;
		} catch (FileNotFoundException e) {
			logger.error(e);
			throw e;
		} catch (NumberFormatException e) {
			logger.error(e);
			throw e;
		} catch (IOException e) {
			logger.error(e);
			throw e;
		}
	}
	

	public static void main(String[] args){
		ParseUinListJob job = new ParseUinListJob();
		job.stat(args);
	}
}
